package com.swss.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;

public class FileHelper {
	// 获取以年月日为目录的字符串
	public static String getDirName() {
		return "\\upload\\"
				+ new SimpleDateFormat("yyyy-MM").format(new Date());
	}

	// 获取毫秒级字符串 作为文件名
	public static String getNewFileName(String oldName) {
		return oldName.replaceAll("(.*?\\.)", new SimpleDateFormat(
				"yyyyMMddHHmmssSSS").format(new Date())
				+ ".");
	}

	/**
	 * 保存多个文件并返回 全路径
	 * 
	 * @param files
	 * @param fileNames
	 * @param realPath
	 * @return
	 */
	public static String saveFiles(File[] files, String[] fileNames,
			String realPath) {

		try {
			StringBuffer urls = new StringBuffer();
			String targetFileName = null;
			File targetFile = null;
			String targetDirectory = getDirName();

			for (int i = 0; i < files.length; i++) {
				targetFileName = getNewFileName(fileNames[i]);
				targetFile = new File(realPath + targetDirectory,
						targetFileName);

				if (!targetFile.getParentFile().exists()) {
					targetFile.getParentFile().mkdirs();
				}
				FileUtils.copyFile(files[i], targetFile);

				if (i > 0) {
					urls.append(",");
				}

				urls.append(targetDirectory);
				urls.append("\\");
				urls.append(targetFileName);

			}
			return urls.toString().replaceAll("\\\\", "/");
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}

	}

	public static String saveFile(File file, String fileName, String realPath) {

		try {
			StringBuffer url = new StringBuffer();
			String targetFileName = null;
			File targetFile = null;
			String targetDirectory = getDirName();

			targetFileName = getNewFileName(fileName);
			targetFile = new File(realPath + targetDirectory, targetFileName);

			if (!targetFile.getParentFile().exists()) {
				targetFile.getParentFile().mkdirs();
			}
			FileUtils.copyFile(file, targetFile);

			url.append(targetDirectory);
			url.append("\\");
			url.append(targetFileName);

			return url.toString().replaceAll("\\\\", "/");
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}

	}

	public static boolean deleteFile(String realPath,String sPath) {
		Boolean flag = false;
		File file = new File(realPath+sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}
}
